/*
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.
*/
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

class Solution {
private:
	vector<string> result;
	void GenerateNextString(const string& str, string* next_str) {
		stringstream ss;
		char last_ch = str[0];
		int count = 1;
		for (int i = 1; i < str.size(); i++) {
			if (str[i] == last_ch)
				count++;
			else {
				ss << count << last_ch;
				last_ch = str[i];
				count = 1;
			}
		}
		ss << count << last_ch;
		next_str->append(ss.str());
	}
public:
	Solution() {
		result.push_back("1");
	}
    string countAndSay(int n) {
    	if (n == result.size()) {
    		return result[n - 1];
    	}
    	string cur_str = result.back();
    	string next_str;
    	for (int i = result.size(); i < n; i++) {
    		GenerateNextString(cur_str, &next_str);
    		result.push_back(next_str);
    		cur_str = next_str;
    		next_str.clear();
    	}
    	return result[n - 1];
    }
};

int main(int argc, char* argv[])
{
	Solution s;
	for (int i = 1; i < 6; i++)
		cout << s.countAndSay(i) << endl;
	return 0;
}